﻿using System.Collections.Generic;
using System.Linq;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;
using Fuse8.GlobalizationFramework.Domain;
using Fuse8.GlobalizationFramework.Domain.Commands;

namespace Fuse8.GlobalizationFramework.DataAccess.SqlRepository
{
    internal class ResourceByKeyAndLocaleSqlCommand : ResourceByKeyAndLocale
    {
        public override Resource ExecuteOne()
        {
            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<Resource>>();
            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<Resource>;
            IEnumerable<Resource> result = null;
            if (currentUnitOfWork != null)
            {
                var mapper = DependencyServiceLocator.Current.GetInstance<ISqlEntityDataMapper<Resource, int>>();

                result = SqlUtility<Resource, int>.ExecuteReader(currentUnitOfWork.Connection,
                                                                 currentUnitOfWork.Transaction,
                                                                 "gf_usp_ResourceGetByKeyAndLocale", new {Key, Locale},
                                                                 mapper);
            }

            return result != null ? result.FirstOrDefault() : null;
        }
    }
}